package com.lanyun.core.encrypt.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.MDC;

import javax.annotation.Resource;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @ClassName：EncryptTypeHandler
 * @Description: 实现数据库的字段保存加密与查询解密处理类
 * @Author: Jqcc
 * @Date: 2025/3/13
 */
@Slf4j
public class EncryptTypeHandler<T> extends BaseTypeHandler<T> {

    /**
     * MDC中加密标识
     */
    private static final String ENCRYPTTYPE = "ENCRYPTTYPE";

    /**
     * 增加忽略
     */
    public static void ignoreEncrypt() {
        MDC.put(ENCRYPTTYPE, "1");
    }

    /**
     * 清理忽略
     */
    public static void cleanIgnore() {
        MDC.remove(ENCRYPTTYPE);
    }

    /**
     * 检查是否忽略
     *
     * @return
     */
    private Boolean checkIgnore() {
        if (MDC.get(ENCRYPTTYPE) == null) {
            return false;
        }
        return true;
    }


    @Resource
    private EncryptHandler encryptHandler;

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, encrypt((String) parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        //有一些可能是空字符
        return StringUtils.isBlank(columnValue) ? (T) columnValue : (T) decrypt(columnValue);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        return StringUtils.isBlank(columnValue) ? (T) columnValue : (T) decrypt(columnValue);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String columnValue = cs.getString(columnIndex);
        return StringUtils.isBlank(columnValue) ? (T) columnValue : (T) decrypt(columnValue);
    }

    private String encrypt(String text) {
        if (Objects.isNull(encryptHandler) || StringUtils.isBlank(text)) {
            return text;
        }
        if (checkIgnore()) {
            return text;
        }
        // 实现加密逻辑
        // 假设返回加密后的字符串
//        return Base64.getEncoder().encodeToString(text.getBytes());
        return encryptHandler.encrypt(text);
    }

    private String decrypt(String text) {
        if (Objects.isNull(encryptHandler) || StringUtils.isBlank(text)) {
            return text;
        }
        if (checkIgnore()) {
            return text;
        }
        // 实现解密逻辑
        // 假设返回解密后的字符串
//        byte[] decode = Base64.getDecoder().decode(text);
//        return new String(decode, StandardCharsets.UTF_8);
        return encryptHandler.decrypt(text);
    }
}

